package parser;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class InputEntity {
	
	// pointer to current phrase position in file
	private int curStart = 0;
	private int curEnd = 0;
	
	// current document counter
	private int doc = 1;
	
	// a matcher and pattern for the current phrase
	private Matcher strMatcher;
	private Pattern strPattern;
	
	// the previously read character
	private char prevChar;
	
	// current processed phrase
	private String currentPhrase;
	
	// input stream
	private FileInputStream fis;
	
	public void open(String fn) {
		
		File file = new File(fn);
	    if (!file.exists()) {
	      System.out.println(fn + " does not exist.");
	      System.exit(-1);
	    }
	    if (!(file.isFile() && file.canRead())) {
	      System.out.println(file.getName() + " cannot be read from.");
	      System.exit(-1);
	    }
	    try {
	      fis = new FileInputStream(file);
	      
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	}
	
	public void initMatcher(String match) {
		strPattern = Pattern.compile(match,'i'); // match case insensitive
		strMatcher = strPattern.matcher(currentPhrase);
	}
	
	public int getNextStartIndex() {
		if(strMatcher.find()) {
			return curStart + strMatcher.start() - 1;
		}
		else {
			return -1;
		}
	}
	
	public int getDocID() {
		return doc;
	}
	
	public boolean hasPhrase() {
		try {
			return (fis.available() > 0);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
	public String nextPhrase() {
		
		char currentChar = "a".charAt(0); // init value - just important that its not a capital letter!
		currentPhrase = "";
		try {
			
			// set the start pointer
			curStart = curEnd;
			
			while (fis.available() > 0) {
				prevChar = currentChar;
				currentChar = ((char) fis.read());
				currentPhrase += currentChar;
				curEnd++;
				// when we got a new line we got a new document
				if(currentChar == "\n".charAt(0)) {
					// increment doc counter and reset indexes
					doc++;
					curStart = 0;
					curEnd = 0;
				}
				// We assume a sentence ends with either '.', '?' or '!'
				// Careful: We also have to take into account names such as B. Gates
				if(currentChar == "?".charAt(0) || currentChar == "!".charAt(0)) {
					break;
				}
				if(currentChar == ".".charAt(0)) {
					// if the previous character is upper case, we assume a shortcut name
					if(!Character.isUpperCase(prevChar)) {
						break;
					}
				}
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return currentPhrase;
	}
}
